package com.loren.demo19.service;

import com.loren.demo19.lock.RedisLock;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@AllArgsConstructor
public class SeckillService {

    /**
     * 库存量
     */
    private static int STOCK = 50;

    private final RedisLock redisLock;

    public String seckill(String key, String value) {
        if (STOCK == 0) {
            return "商品已售罄";
        }
        boolean lock = this.redisLock.lock(key, value, 5L, TimeUnit.SECONDS);
        if (lock) {
            try {
                // 阻塞1秒钟模拟订单的处理
                Thread.sleep(1000);
                STOCK = STOCK - 1;
                log.info("{} 成功秒杀商品，库存剩余：{}", value, STOCK);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                this.redisLock.unLock(key, value);
            }
            return "秒杀成功";
        }
        return "秒杀失败";
    }
}
